class Table {
    constructor(top,title) {
        this.title = title || '';
        this.tableHead = null;
        this.tableBody = null;
        this.headerList = null;
        this.tableList = null;
        this.init(top);
    }

    init(top) {
        $(document.head).append(`<style>
.table-area {
    position: relative;
    width: 100%;
    height: 100%;
    padding: 10px;
    box-sizing: border-box;
}
.table-title {
    position: relative;
    width: 100%;
    height: 30px;
    line-height: 30px;
    font-size: 18px;
}
.table-table {
    position: relative;
    width: 100%;
    table-layout: fixed;
    /*height: calc(100% - 30px);*/
}
.table-table thead th {
    line-height: 20px;
    height: 20px;
    text-align: center;
    font-size: 16px;
}
.table-table tbody tr {
    height: 20px;
}
.table-table tbody tr td {
    line-height: 20px;
    height: 20px;
    text-align: center;
    font-size: 16px;
}
.table-table-content::-webkit-scrollbar-track-piece {
    background-color:#f8f8f8;
}
.table-table-content::-webkit-scrollbar {
    width:1px;
    height:9px;
}
.table-table-content::-webkit-scrollbar-thumb {
    background-color:#dddddd;
    background-clip:padding-box;
    min-height:28px;
}
.table-table-content::-webkit-scrollbar-thumb:hover {
    background-color:#bbb;
}
</style>`)
        $(top).append(`<div class="table-area">
<div class="table-title">${this.title}</div>
<div style="line-height: 26px;height: 26px;">
<table class="table-table">
<colgroup tar="colgroup">
<!--<col name="el-table_1_column_1" width="">-->
</colgroup>
<thead class="table-table-head">
<!--    <th>a</th>-->
</thead>
</table>
</div>
<div class="table-table-content" style="overflow-x:hidden;overflow-y:scroll;height: calc(100% - 56px);">
<table class="table-table">
<colgroup tar="colgroup">
</colgroup>
<tbody class="table-table-body">
<!--<tr></tr>-->
</tbody>
</table>
</div>
</div>`);
        this.tableHead = $('.table-table-head')[0];
        this.tableBody = $('.table-table-body')[0];
    }

    removeTr(row) {
        let tr = $(`tr[trId="${row.id}"]`)[0];
        tr.style.display = 'none';
    }
    updateTr(row,add) {
        if (add) {
            $(this.tableBody).append($(`<tr trId="${row.id}" trIndex="${this.tableList.length}"></tr>`));
            this.tableList.push(row);
        }
        let tr = $(`tr[trId="${row.id}"]`)[0];
        let index = tr.getAttribute('trIndex');
        let rnd = `action_${new Date().getTime()}_${parseInt(Math.random() * 1000)}`;
        this.tableList[index] = row;
        tr.innerHTML = this.headerList.map((li,hIndex) => {
            let text = '';
            if (li.name === '#index') {
                text = index + 1;
            } else if (li.name) {
                text = row[li.name];
            } else {
                text = li.fn(index,row,this.tableList);
            }
            return `<td action="${li.action ? 'action' : 'none'}" row="${rnd}" index="${index}" hIndex="${hIndex}" class="col_group_${hIndex}">${text}</td>`;
        }).join('');
        $(this.tableBody).find('[action="action"]').each((tdIndex,td) => {
            let action = td.getAttribute('action');
            if (action !== 'none') {
                td.setAttribute('action','none');
                let index = +td.getAttribute('index');
                let hIndex = +td.getAttribute('hIndex');
                td.style.cursor = 'pointer';
                td.onclick = (function (index,list,action) {
                    action(index,list);
                }).bind(td,index,this.tableList,this.headerList[hIndex].action);
            }
        });
    }

    // headerList = [
    //      // name 和 fn 二选一，优先为 name，表示从 数组对象中获取的属性名
    //      // fn 的三个参数分别是，当前的索引，当前行的数据和全部数据
    //      // action 是点击该项时的动作
    //  { title: '',name: '',fn(index,row,list) {return row.toString();}, action(index,list) {  }, class: '', style: '' }
    //      // 例如 { title: '标题', name: 'id' }
    //      // 其他特定的表头如下
    //  { title: '',name: '#index', action(index,list) {  }, class: '', style: '' } // 索引（title 可以自定义）
    // ]
    //  action 的参数： index 当前行索引，list 所有数据
    // tableList = [
    //  { id: '' }
    // ]
    setData(headerList,tableList) {
        this.headerList = headerList;
        this.tableList = tableList;
        let _createColGroup = () => {
            $('[tar="colgroup"]').append(headerList.map((_,ind) => `<col name="col_group_${ind}">`).join('\r\n'));
        };
        let _createHeader = (h,ind) => {
            return `<th class="${h.class} col_group_${ind}" style="${h.style}">${h.title}</th>`;
        }
        let rnd = `action_${new Date().getTime()}_${parseInt(Math.random() * 1000)}`;
        // let actions = [];
        let _createTr = (index) => {
            let row = tableList[index];
            // let id = `${row}_${index}`;
            // actions.push([row,index,tableList])
            let tr = `<tr trId="${row.id || ''}" trIndex="${index}">` + headerList.map((li,hIndex) => {
                let text = '';
                if (li.name === '#index') {
                    text = index + 1;
                } else if (li.name) {
                    text = row[li.name];
                } else {
                    text = li.fn(index,row,tableList);
                }
                return `<td action="${li.action ? 'action' : 'none'}" row="${rnd}" index="${index}" hIndex="${hIndex}" class="col_group_${hIndex}">${text}</td>`;
            }).join('') + `</tr>`;
            // console.log(tr);
            // let action = (function (row,index,list) {}).bind(null,tableList[index],index,tableList);
            return tr;
        }
        _createColGroup();
        $(this.tableHead).append($(headerList.map(_createHeader).join('\r\n')));
        $(this.tableBody).append($(tableList.map((_,ind) => _createTr(ind)).join('\r\n')));
        $(this.tableBody).find('[action="action"]').each((tdIndex,td) => {
            td.setAttribute('action','none');
            let index = +td.getAttribute('index');
            let hIndex = +td.getAttribute('hIndex');
            td.style.cursor = 'pointer';
            td.onclick = (function (index,list,action) {
                action(index,list);
            }).bind(td,index,tableList,headerList[hIndex].action);
        });
    }
}
